/*
 * Copyright 2023-2085 xujin <ceo@itgrail.com>
 *
 * Licensed under the Grail License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://itgrail.com/docs?id=3&catalogId=87
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.itgrail.pilot.app.command;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.base.Preconditions;
import com.itgrail.pilot.app.command.cmo.AddUserOkrAlignCmd;
import com.itgrail.pilot.app.converter.UserOkrAlginClientConverter;
import com.itgrail.pilot.domain.user.entity.ObjectiveE;
import com.itgrail.pilot.domain.user.entity.UserOkrAlignE;
import com.itgrail.pilot.domain.user.factory.ObjectiveFactory;
import com.itgrail.pilot.domain.user.ports.ObjectivePort;
import com.itgrail.pilot.infrastructure.tunnel.db.dao.ObjectiveMapper;
import com.itgrail.pilot.infrastructure.tunnel.db.dao.UserOkrAlignMapper;
import com.itgrail.pilot.infrastructure.tunnel.db.dataobject.ObjectiveDO;
import com.itgrail.pilot.infrastructure.tunnel.db.dataobject.UserOkrAlignDO;
import org.springframework.beans.factory.annotation.Autowired;
import com.itgrail.grail.cqrs.annotation.CmdHandler;
import com.itgrail.grail.cqrs.command.CommandExecutorI;
import com.itgrail.grail.dto.ResultData;
import com.itgrail.grail.exception.BusinessException;


@CmdHandler
public class AddUserOkrAlginCmdExe implements CommandExecutorI<ResultData<Integer>, AddUserOkrAlignCmd> {

    @Autowired
    private UserOkrAlginClientConverter converter;

    @Autowired
    private UserOkrAlignMapper userOkrAlignMapper;

    @Autowired
    private ObjectiveMapper objectiveMapper;

    @Autowired
    private ObjectivePort objectivePort;

    @Autowired
    private ObjectiveFactory objectiveFactory;

    @Override
    public ResultData execute(AddUserOkrAlignCmd cmd) {
        ResultData resultData = ResultData.success(null);
        check(cmd);
        //校验okr是否存在   并且是否存在绑定关系
        UserOkrAlignE userOkrAlignE = converter.addClientToEntity(cmd);
        UserOkrAlignE checkResult = checkRelation(userOkrAlignE);
        if (checkResult.getId() != null) {
            if (checkResult.getId() == 1) {
                throw new BusinessException("500", "OKR不存在");
            } else if (checkResult.getId() == 2) {
                throw new BusinessException("500", "OKR已存在绑定关系");
            } else {
                throw new BusinessException("500", "OKR已被对方对齐，不能反向绑定关系");
            }
        }
        //不能自己对齐自己
        if (!canAlign(cmd)) {
            throw new BusinessException("500", "不能向自己对齐");
        }
        userOkrAlignE.setCreated(cmd.getStartObjectiveId());
        int save = userOkrAlignE.save();
        //更新objective对齐人员数量
        updateAlignCount(cmd.getAcceptObjectiveId());
        resultData.setData(save);
        return resultData;
    }

    protected boolean check(AddUserOkrAlignCmd cmd) {
        Preconditions.checkNotNull(cmd, "cmd不能为null");
        Preconditions.checkNotNull(cmd.getAcceptObjectiveId(), "被对齐okrId不能为null");
        Preconditions.checkNotNull(cmd.getStartObjectiveId(), "对齐okrId不能为null");
        Preconditions.checkNotNull(cmd.getOkrPeriod(), "对齐okrId不能为null");
        return true;
    }

    protected void updateAlignCount(Integer id) {
        ObjectiveDO objectiveDO = objectiveMapper.selectById(id);
        ObjectiveE objectiveE = objectiveFactory.createObjectiveE();
        objectiveE.setId(objectiveDO.getId());
        objectiveE.setAlignCount(objectiveDO.getAlignCount() + 1);
        objectivePort.update(objectiveE);
    }

    protected boolean canAlign(AddUserOkrAlignCmd cmd) {
        boolean canAlign = true;
        ObjectiveDO startObject = objectiveMapper.selectById(cmd.getStartObjectiveId());
        ObjectiveDO acceptObject = objectiveMapper.selectById(cmd.getAcceptObjectiveId());
        if (null != startObject && null != acceptObject && startObject.getCreated().equals(acceptObject.getCreated())) {
            canAlign = false;
        }
        return canAlign;
    }

    /**
     * 判断okr的绑定关系
     *
     * @param userOkrAlignE
     * @return
     */
    protected UserOkrAlignE checkRelation(UserOkrAlignE userOkrAlignE) {
        //判断okr是否存在
        ObjectiveDO startObjective = objectiveMapper.selectById(userOkrAlignE.getStartObjectiveId());
        ObjectiveDO acceptObjective = objectiveMapper.selectById(userOkrAlignE.getAcceptObjectiveId());
        if (null != startObjective &&
                null != acceptObjective &&
                userOkrAlignE.getOkrPeriod().equals(startObjective.getOkrPeriodId()) &&
                userOkrAlignE.getOkrPeriod().equals(acceptObjective.getOkrPeriodId())) {
            //当前okr存在 判断绑定关系是否存在
            LambdaQueryWrapper<UserOkrAlignDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserOkrAlignDO::getOkrPeriod, userOkrAlignE.getOkrPeriod());
            queryWrapper.eq(UserOkrAlignDO::getStartObjectiveId, userOkrAlignE.getStartObjectiveId());
            queryWrapper.eq(UserOkrAlignDO::getAcceptObjectiveId, userOkrAlignE.getAcceptObjectiveId());
            UserOkrAlignDO userOkrAlignDO = userOkrAlignMapper.selectOne(queryWrapper);
            if (userOkrAlignDO != null) {
                userOkrAlignE.setId(2);
            } else {
                //当前okr是否被反向绑定
                queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(UserOkrAlignDO::getOkrPeriod, userOkrAlignE.getOkrPeriod());
                queryWrapper.eq(UserOkrAlignDO::getStartObjectiveId, userOkrAlignE.getAcceptObjectiveId());
                queryWrapper.eq(UserOkrAlignDO::getAcceptObjectiveId, userOkrAlignE.getStartObjectiveId());
                userOkrAlignDO = userOkrAlignMapper.selectOne(queryWrapper);
                //如果不存在  返回
                if (null == userOkrAlignDO) {
                    userOkrAlignE.setAcceptUserId(acceptObjective.getCreated());
                    userOkrAlignE.setStartUserId(startObjective.getCreated());
                    return userOkrAlignE;
                }
                userOkrAlignE.setId(3);
            }
        } else {
            userOkrAlignE.setId(1);
        }
        return userOkrAlignE;
    }

}
